#!/bin/bash

DATA_PATH="$HOME/czyhome/minio/data"
CONFIG_PATH="$HOME/czyhome/minio/config"
IMAGE_NAME="minio/minio"
MINIO_SERVER_NAME="minio"
BUCKET_NAME="mybucket"

export MINIO_ROOT_USER="admin"
export MINIO_ROOT_PASSWORD="miniopasswd"

# 判断minio是否存在，不存在就pull下来
if docker images --format "{{.Repository}}" | grep -q "^$IMAGE_NAME$"
then
	echo "docker image $IMAGE_NAME is exist"
else
    docker pull minio/minio
fi

# 判断minio client是否存在，不存在则下载
if which mc >/dev/null
then
	echo "minio client is exist"
else
	wget -P /usr/local/bin http://dl.minio.org.cn/client/mc/release/linux-amd64/mc
	chmod +x /usr/local/bin/mc
	echo "installed minio client"
fi

# 判断minio的data path是否存在
if [ ! -d $DATA_PATH ]; then
	mkdir -p $DATAPATH
# else
# 	sudo rm -rf $DATAPATH
fi
# 判断minio的config path是否存在
if [ ! -d $CONFIG_PATH ]; then
	mkdir -p $CONFIG_PATH
# else
# 	sudo rm -rf $CONFIG_PATH
fi

# nohup minio server $DATAPATH --console-address ":9001" > minio_server.log 2>&1 &

# 启动minio容器
if docker ps -a --filter "name=$MINIO_SERVER_NAME" --filter "status=running" --format "{{.Names}}" | grep -q "^$MINIO_SERVER_NAME$"
then
    echo "Docker container '$MINIO_SERVER_NAME' is running"
else
    echo "Docker container '$MINIO_SERVER_NAME' is not running, start it now"
	docker rm $MINIO_SERVER_NAME
	docker run --name $MINIO_SERVER_NAME \
		-p 9000:9000 \
		-p 9999:9999 \
		-d --restart=always \
		-e "MINIO_ROOT_USER=$MINIO_ROOT_USER" \
		-e "MINIO_ROOT_PASSWORD=$MINIO_ROOT_PASSWORD" \
		-v $DATA_PATH:/data \
		-v $CONFIG_PATH:/root/.minio \
		minio/minio server /data \
		--console-address '0.0.0.0:9999'
fi

sleep 1s

# 配置客户端，添加minio服务
if ! mc config host list | grep $MINIO_SERVER_NAME ; then
	echo "add minio for mc"
	mc config host add $MINIO_SERVER_NAME http://127.0.0.1:9000 $MINIO_ROOT_USER $MINIO_ROOT_PASSWORD
	if [ $? -ne 0 ] ; then
		echo "mc config error"
	fi
fi

# 不存在特定bucket就创建
if ! mc ls $MINIO_SERVER_NAME | grep $BUCKET_NAME ; then
	echo "$MINIO_SERVER_NAME is not exist, create it now"
	mc mb $MINIO_SERVER_NAME/$BUCKET_NAME
else
	echo "$MINIO_SERVER_NAME/$BUCKET_NAME is exist"
fi
